package StructuralPattern.FlyWeight;

/**
 * @Classname : FlyWeightClient
 * @Description : 测试 享元模式
 * 一、模式定义
 *   Use sharing to support large numbers of fine-grained objects efficiently.
 *   使用共享对象来高效地支持大量的细粒度的对象。
 *   优点：对象共享，降低程序内存占用。
 *   缺点：需要区分内部状态和外部状态，增加系统复杂度。
 *   注意：为避免线程安全问题，不用将外部状态存入对象内部，尽量使用享元对象执行操作时实时传入外部状态。
 * 二、模式类图
 *   https://kdocs.cn/l/coXpujyO4vlW
 * 三、适用场景
 *   1、当系统中存在大量相似对象，占用内存过大时
 *
 * 四、应用举例
 *   1、字符串池
 *
 * @Author : chentianyu
 * @Date 2023/2/23 21:34
 */


public class FlyWeightClient {
    public static void main(String[] args) {
        // 内部状态（数量有限）
        String white = "白色";
        String black = "黑色";

        System.out.println("—————————享元模式共享对象————————");
        FlyWeight flyWeight = FlyWeightFactory.getFlyWeight(white);
        System.out.println(flyWeight);
        flyWeight.operate(0, 0);
        FlyWeight flyWeight2 = FlyWeightFactory.getFlyWeight(white);
        System.out.println(flyWeight2);  // flyWeight 和 flyWeight2 应指向同一对象
        flyWeight.operate(0, 1);

        System.out.println("—————————不共享对象————————");
        UnsharedConcreteFlyWeight flyWeight3 = new UnsharedConcreteFlyWeight(black, 6, 6);
        System.out.println(flyWeight3);
        flyWeight3.operate();
        UnsharedConcreteFlyWeight flyWeight4 = new UnsharedConcreteFlyWeight(black, 6, 7);
        System.out.println(flyWeight4);  // flyWeight3 和 flyWeight4 应指向不同对象
        flyWeight4.operate();
    }
}

/** 20220223
 * —————————享元模式共享对象————————
 * StructuralPattern.FlyWeight.ConcreteFlyWeight@232204a1
 * 白色棋子落子位置 (0, 0)
 * StructuralPattern.FlyWeight.ConcreteFlyWeight@232204a1
 * 白色棋子落子位置 (0, 1)
 * —————————不共享对象————————
 * StructuralPattern.FlyWeight.UnsharedConcreteFlyWeight@7ea987ac
 * 黑色棋子落子位置 (6, 6)
 * StructuralPattern.FlyWeight.UnsharedConcreteFlyWeight@12a3a380
 * 黑色棋子落子位置 (6, 7)
 */
